<?php
namespace app\modules\v1\controllers;

use app\common\ApiResponse;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\Cors;
use yii\filters\RateLimiter;

/**
 * Api请求响应基类
 * 定义相关的认证方式、速率等
 */
class ApiBaseController extends \yii\rest\Controller
{


    public function behaviors(): array
    {
        $behaviors = parent::behaviors();

        // 配置跨域
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Methods' => ['*'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
            ]
        ];

        // 配置认证
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                //配置API接口认证方式
                QueryParamAuth::class, // url中追加access-token=XXX
                HttpBearerAuth::class,  // Header 中追加Key：Authorization，Value：Bearer XXXX
            ],
        ];

        // 开启速率限制
        $behaviors['rateLimiter'] = [
            'class' => RateLimiter::class,
            'enableRateLimitHeaders' => true,
        ];

        return $behaviors;
    }

    /**
     * @var ApiResponse
     */
    protected ApiResponse $_api;

    /**
     * @param $id
     * @param $module
     * @param $config
     */
    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->_api = new ApiResponse();
    }

    public function actionIndex(): array
    {
        return $this->_api->success([
            'authMethods' => [
                'HttpBearerAuth',
                'QueryParamAuth',
            ]
        ]);
    }

    public function actionImportExpressCompany()
    {
        $str_filename = \Yii::$app->basePath."/../carriers.csv";
        if(!file_exists($str_filename))
        {
            return "file_path:".$str_filename;
        }

        $file_data = file_get_contents($str_filename);
        $file_rows = explode("\r\n",$file_data);
        $str_error_file = \Yii::$app->basePath."/../carriers_err.csv";
        foreach($file_rows as $row )
        {
//            var_dump($row);
            if($row == "") continue;
            list($key,$name_en,$name_cn,$name_hk,$url) = explode(",",$row);
            $name_en =  trim(str_replace('"','',$name_en));
            $name_cn =  trim(str_replace('"','',$name_cn));
            $sql = "select * from cod_express_company where company_code like '%".$name_en."%' or company_name like '%".$name_cn."%'";
//            print_r($sql);
            $rd = \Yii::$app->db->createCommand($sql)->queryAll();
            if( empty($rd) || 0==count($rd) )
            {
                file_put_contents($str_error_file,$row."\r\n",FILE_APPEND);
                continue;
            }

            $key = trim(str_replace('"','',$key));
            if(1==count($rd))
            {
                $sql = "update cod_express_company set company_code_17t='".$key."'  where express_companyid=".$rd[0]['express_companyid'];
                \Yii::$app->db->createCommand($sql)->execute();
                continue;
            }

            $bl = false;
            foreach($rd as $record){
                if($record['company_code'] == $name_en || $record['company_name'] == $name_cn ){
                    $sql = "update cod_express_company set company_code_17t='".$key."'  where express_companyid=".$record['express_companyid'];
                    \Yii::$app->db->createCommand($sql)->execute();
                    $bl = true;
                    break;
                }
            }
            if(!$bl) file_put_contents($str_error_file,$row."\r\n",FILE_APPEND);
        }
    }


}